<template>
  <div>
    <div class="titFirst">
      <div><i class="iconfont icon-shixinyuan"></i>农资类型管理</div>
      <div
        style="display:flex;justify-content: space-around;align-items: center;"
      >
        <el-button type="primary" @click="newList">新&nbsp;&nbsp;增</el-button>
        <el-button :disabled="!enableDel" type="danger" @click="remove"
          >删&nbsp;&nbsp;除</el-button
        >
        <!--        <div class="btn_purpose_left" @click="newList">新增</div>-->
        <!--        <div class="btn_purpose_right" @click="remove">删除</div>-->
      </div>
    </div>
    <div>
      <div class="block">
        <el-tree
          :data="dataList"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="defaultProps"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          @check-change="danxuan"
          ref="tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                type="text"
                size="mini"
                @click="append(data)"
                style="margin-right: 20px;"
              >
                <i class="iconfont icon-chilun"></i>
              </el-button>
              <!-- <el-button
                type="text"
                size="mini"
                @click="() => remove(node, data)"
              >
                Delete
              </el-button> -->
            </span>
          </span>
        </el-tree>
        <!--修改信息--->
        <el-dialog
          title="修改农资"
          :visible.sync="dialogVisible"
          width="40%"
          :close-on-click-modal="false"
        >
          <el-form
            ref="subscriberFormData"
            :model="fromData"
            label-width="80px"
            :rules="subscriberDataRules"
            style="padding-right: 20px"
          >
            <el-form-item label="农资" prop="goodName">
              <el-input
                v-model="fromData.goodName"
                placeholder="农资名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="计量单位" prop="orderNum" v-show="unitShow">
              <el-select v-model="fromData.unit" placeholder="请选择">
                <el-option
                  v-for="item in options_4"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="序号" prop="orderNum">
              <el-input-number
                v-model="fromData.orderNum"
                :min="1"
                :max="1000"
                label="序号"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <div
              style="display: flex;justify-content: flex-end;padding-right: 20px;margin-top: -36px"
            >
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="sendInfo">确 定</el-button>
            </div>
          </span>
        </el-dialog>
        <!----新增------>
        <el-dialog
          title="新增农资"
          :visible.sync="addNews"
          width="40%"
          :close-on-click-modal="false"
        >
          <div class="block">
            <el-form
              ref="subscriberForm"
              label-width="80px"
              :model="from"
              :rules="subscriberRules"
              style="padding-right: 20px"
            >
              <el-form-item label="父级" prop="parentId">
                <el-cascader
                  style="width: 100%"
                  :options="seleList"
                  :props="{
                    checkStrictly: true,
                    value: 'id',
                    label: 'goodName',
                    children: 'children',
                    expandTrigger: 'hover'
                  }"
                  clearable
                  ref="cascaderAddr"
                  @change="newSelet"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="计量单位" prop="orderNum">
                <el-select
                  v-model="from.unit"
                  placeholder="请选择"
                  :disabled="disable"
                  ref="unit"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="农资" prop="goodName">
                <el-input
                  v-model.trim="from.goodName"
                  placeholder="农资名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="序号" prop="orderNum">
                <el-input-number
                  v-model="from.orderNum"
                  :min="1"
                  :max="1000"
                  label="序号"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-form>

            <span slot="footer">
              <div
                style="display: flex;justify-content: flex-end;padding-right: 20px;margin-top: 30px"
              >
                <el-button @click="addNews = false">取 消</el-button>
                <el-button type="primary" @click="delivery">确 定</el-button>
              </div>
            </span>
          </div>
        </el-dialog>
        <!--删除--->
        <!--        <el-dialog title="是否删除" :visible.sync="delet">-->
        <!--          <div v-for="(item, index) in deleArry" :key="index">-->
        <!--            <div>{{ item.label }}</div>-->
        <!--          </div>-->
        <!--          <el-button type="primary" @click="deleClick">确认删除</el-button>-->
        <!--        </el-dialog>-->
      </div>
    </div>
  </div>
</template>

<script>
// let id = 1000;
import "@/icon/iconfont.css";
import PubSub from "pubsub-js";
import {
  newaddMaterial,
  typelistMaterial,
  checkmaterialList,
  reviseMaterial,
  deleteMaterial,
  checkMaterial
} from "@/api/material";
import { dictionariesCheck } from "@/api/dictionaries";
import { set } from "date-fns";
export default {
  props: ["name"],
  created() {
    this.queryList();
    dictionariesCheck("metering_unit").then(res => {
      console.log(res);
      this.options = res.data.data;
      this.options_4 = res.data.data;
    });
  },
  data() {
    const validateEditName = (rule, value, callback) => {
      if (
        this.fromData.goodName == null ||
        this.fromData.goodName == undefined ||
        this.fromData.goodName === ""
      ) {
        callback(new Error("请输入农资名称"));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (
        this.from.goodName == null ||
        this.from.goodName == undefined ||
        this.from.goodName === ""
      ) {
        callback(new Error("请输入农资名称"));
      } else {
        callback();
      }
    };
    const validateParent = (rule, value, callback) => {
      if (this.from.parentId != null || this.from.parentId == "") {
        callback();
      } else {
        callback(new Error("请选择父级"));
      }
    };
    return {
      disable: true,
      wzParentId: "",
      wzId: "",
      value: "",
      options: [],
      list: [],
      fromData: {
        goodName: "",
        orderNum: "",
        unit: ""
      },
      lastArr: [],
      enableDel: false,
      childArr: [],
      dataList: [],
      danwei: "",
      from: {
        goodName: "",
        parentId: "",
        unit: ""
      },
      unitShow: false,
      seleList: [],
      sortMenu: "",
      delet: false,
      saveId: [],
      deleArry: [],
      options_4: [],
      xzInput: "",
      addNews: false,
      targetNode: null,
      dialogVisible: false,
      defaultProps: {
        children: "children",
        label: "goodName"
      },
      subscriberDataRules: {
        goodName: [
          {
            validator: validateEditName,
            trigger: "blur",
            required: true
          }
        ]
      },
      subscriberRules: {
        goodName: [
          {
            validator: validateName,
            trigger: "blur",
            required: true
          }
        ],
        parentId: [
          {
            validator: validateParent,
            trigger: "blur",
            required: true
          }
        ]
      }
    };
  },
  watch: {
    lastArr: {
      handler(n, o) {
        this.enableDel = n && n.length > 0;
      },
      immediate: true
    },
    dialogVisible: {
      handler(n, o) {
        if (!n) {
          this.$nextTick(() => {
            Object.assign(this.$data.fromData, this.$options.data.fromData);
            this.$refs.subscriberFormData.resetFields();
          });
        }
      }
    },
    addNews: {
      handler(n, o) {
        if (!n) {
          this.$nextTick(() => {
            Object.assign(this.$data.from, this.$options.data.from);
            this.$refs.subscriberForm.resetFields();
          });
        }
      }
    }
  },
  methods: {
    deleClick() {
      this.delet = false;
      const loading = this.$load(this);
      deleteMaterial(this.lastArr.toString()).then(res => {
        this.lastArr = [];
        loading.close();
        if (res.data.code == 200) {
          this.$message({
            type: "success",
            message: res.data.msg
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
        this.queryList();
      });
    },
    resetPlace() {
      const _cascader = this.$refs.cascaderAddr;
      // console.log(_cascader)
      if (_cascader) {
        _cascader.$refs.panel.checkedValue = [];
        _cascader.$refs.panel.activePath = [];
        _cascader.$refs.panel.syncActivePath();
      }
    },
    //重置
    clearList() {
      this.resetPlace();
      this.from = {
        goodName: null,
        orderNum: null,
        parentId: null
      };
      this.fromData = {
        goodName: null,
        orderNum: null,
        unit: null
      };
    },
    //列表查询方法
    queryList() {
      const loading = this.$load(this);
      typelistMaterial({ goodType: "farm_good" }).then(res => {
        loading.close();
        this.dataList = res.data.data;
        let parentObjs = [];
        this.tree2List(JSON.parse(JSON.stringify(this.dataList))).map(item => {
          if (item.children.length > 0) {
            parentObjs.push(item);
          }
        });
        this.childArr = [];
        parentObjs.forEach(i => {
          this.childArr.push(i.id * 1);
        });
      });
    },
    array2String(arr, separator) {
      let text = "";
      if (arr.length == 0) {
        return text;
      } else {
        arr.forEach(item => {
          text = text + item + separator;
        });
        return text.substr(0, text.length - 1);
      }
    },
    tree2List(node) {
      let stack = node,
        data = [];
      while (stack.length != 0) {
        let pop = stack.pop();
        data.push({
          id: pop.id,
          children: pop.children,
          goodName: pop.goodName,
          parentId: pop.parentId
        });
        let children = pop.children;
        if (children) {
          for (let i = children.length - 1; i >= 0; i--) {
            stack.push(children[i]);
          }
        }
      }
      return data;
    },

    danxuan() {
      //   console.log(111111)
      this.handleNodeClick();
    },
    handleNodeClick() {
      //   let itemIds = this.$refs.treel.getCheckedKeys();
      let itemObjs = this.$refs.tree.getCheckedKeys();
      // console.log(itemObjs)
      let resultArr = [];
      itemObjs.forEach(id => {
        if (this.childArr.indexOf(id * 1) == -1) {
          resultArr.push(id);
        }
      });
      // for (var i = 0; i < itemObjs.length; i++) {
      //   if (this.childArr.indexOf(itemObjs[i]) > -1) {
      //     itemObjs.splice(i, i + 1);
      //   }
      // }
      this.lastArr = resultArr;
    },
    newSelet(obj) {
      this.from.parentId = obj[obj.length - 1];
      const _cascader = this.$refs.cascaderAddr;
      if (_cascader.checkedValue.length >= 2) {
        this.disable = true;
        var id = _cascader.checkedValue[1];
        checkMaterial(id).then(res => {
          this.from.unit = res.data.data.unit;
          this.$refs.unit.selectedLabel = res.data.data.unit;
        });
      } else if (_cascader.checkedValue.length == 1) {
        console.log();
        this.disable = false;
      } else {
        this.disable = true;
      }
      //  console.log(_cascader.checkedValue)
      // console.log(obj[obj.length - 1]);
      // console.log(obj);
      // this.$refs.cascaderAddr.getCheckedNodes().forEach(i => {
      //   let a = i.uid;
      //   this.from.parentId = a;
      //   console.log(this.from.parentId);
      // });
    },
    delivery() {
      this.$refs.subscriberForm.validate(valid => {
        if (valid) {
          this.from.goodType = "farm_good";
          const loading = this.$load(this);
          newaddMaterial(this.from).then(res => {
            loading.close();
            if (res.data.code == 200) {
              this.queryList();
              this.$message({
                type: "success",
                message: res.data.msg
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.msg
              });
            }
          });
          this.addNews = false;
        } else {
          return false;
        }
      });
    },
    newList() {
      this.clearList();
      this.$nextTick(() => {
        const loading = this.$load(this);
        typelistMaterial({ goodType: "farm_good" }).then(res => {
          loading.close();
          const rootObj = [
            {
              id: 1,
              path: 0,
              parentId: 0,
              goodType: "farm_good",
              goodName: "农资",
              children: res.data.data
            }
          ];
          this.seleList = rootObj;
          console.log(this.seleList);
          this.addNews = true;
        });
      });
    },
    sendInfo() {
      this.$refs.subscriberFormData.validate(valid => {
        if (valid) {
          this.dialogVisible = false;
          this.targetNode.label = this.info;
          this.fromData.goodType = "farm_good";
          this.fromData.id = this.wzId;
          this.fromData.parentId = this.wzParentId;
          const loading = this.$load(this);
          reviseMaterial(this.fromData).then(res => {
            loading.close();
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: res.data.msg
              });
              this.queryList();
            } else {
              this.$message({
                type: "error",
                message: res.data.msg
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    append(data) {
      if(data.level == 2){
        this.unitShow = true
      }else{
        this.unitShow = false
      }
      console.log(data);
      this.clearList();
      this.fromData.unit = data.unit
      this.targetNode = data;
      this.info = data.label;
      this.dialogVisible = true;
      this.fromData.goodName = data.goodName;
      this.fromData.orderNum = data.orderNum;
      this.wzId = data.id;
      this.wzParentId = data.parentId;
    },
    remove() {
      this.$confirm("此操作将永久删除选中内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleClick();
        })
        .catch(() => {});
      // this.delet = true;
    }
  },
  mounted() {
    PubSub.subscribe("nongjuguanli", (msg, data) => {
      if (data == 0) {
        this.queryList();
      } else {
      }
    });
  },
  beforeDestroy() {
    PubSub.unsubscribe("nongjuguanli");
  }
};
</script>

<style scoped>
.titFirst {
  width: 100%;
  height: 50px;
  line-height: 50px;
  /* background: pink; */
  font-weight: 700;
  font-size: 16px;
}

.titFirst i {
  color: green;
}

.btn_purpose {
  display: flex;
  /* text-align: right; */
  justify-content: flex-end;
  font-size: 16px;
}

.btn_purpose div {
  margin: 10px;
}

.btn_purpose_left {
  width: 80px;
  height: 30px;
  background: green;
  border-radius: 6px;
  line-height: 30px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  color: white;
}

.btn_purpose_right {
  width: 80px;
  height: 30px;
  background: red;
  border-radius: 6px;
  line-height: 30px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  color: white;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.titFirst {
  display: inline-block;
  display: flex;
  justify-content: space-between;
}

.el-tree /deep/ .el-tree-node .el-tree-node__content {
  height: 43px;
  background: #e5f6f0;
  margin: 1px 0;
  color: #007d39;
}

.el-tree /deep/ .is-current > .el-tree-node__content {
  background: rgba(110, 184, 45, 1) !important;
  color: #fff !important;
}

.el-tree /deep/ .el-tree-node__label {
  display: inline-block;
  width: 72%;
}

.el-tree /deep/ .el-tree-node__children .el-tree-node__content {
  height: 34px;
  background: #e4e4e4 !important;
}

.el-tree /deep/ .el-tree-node__children .is-current .el-tree-node__content {
  background: #a5a5a5 !important;
  color: #fff !important;
}

.el-tree /deep/ .el-tree-node__children .el-tree-node__content {
  color: #007d39 !important;
}

.el-tree-node__expand-icon.is-leaf {
  color: transparent !important;
}
</style>
